package com.kfm.mybatis.mapper;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Singleton {

    // 构造私有
    private Singleton(){
        if (instance != null){
            throw new RuntimeException("非法操作");
        }
    }

    private static Singleton instance;

    // 对外提供获取实例的方法
    public static Singleton getInstance(){
        if (instance == null){
            instance = new Singleton();
        }
        return instance;
    }
}

class Demo{

    public static void main(String[] args) {
        Class<Singleton> singletonClass = Singleton.class;

        try {
            Constructor<Singleton> declaredConstructor = singletonClass.getDeclaredConstructor();
            declaredConstructor.setAccessible(true);

            Singleton instance = Singleton.getInstance();
            System.out.println(instance);
            Singleton singleton = declaredConstructor.newInstance();
            System.out.println(singleton);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
